package com.yanlight.app.controller;


import com.aliyuncs.exceptions.ClientException;
import com.yanlight.app.service.CheckCodeService;
import com.yanlight.exception.ErrorType;
import com.yanlight.support.http.Response;
import com.yanlight.util.IpUtil;
import com.yanlight.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

//验证码接口
@Controller
@RequestMapping("/code")
public class CodeController {

    @Autowired
    CheckCodeService checkCodeService;

    @RequestMapping("/getCode")
    @ResponseBody
    public Response getCode(HttpServletRequest request, String tel, String type) {

        if (StringUtils.isBlank(tel) || StringUtils.isBlank(type)) {
            return ResponseUtil.fail(ErrorType.UNLAWFUL_PARAMETERS);
        }

        String ip = IpUtil.getIP(request);
        if (ip.equals("Unknown")) {
            return ResponseUtil.fail(ErrorType.UNLAWFUL_PARAMETERS);
        }

        boolean isCanSend = checkCodeService.canSend(tel, type, ip);
        if (isCanSend) {
            //调用发送验证码的方法
            try {
                Response response = checkCodeService.save(tel, type, ip);
                return response;
            } catch (ClientException e) {
                return ResponseUtil.fail(ErrorType.CHECK_CODE_SEND_ERROR);
            }
        } else {
            return ResponseUtil.fail(ErrorType.CHECK_CODE_LIMIT);
        }
    }

}
